const uuid = require('node-uuid'),
  log = require('../util/log'),
  config = require('../util/config'),
  sessions = []

exports.get = (req, res) => {
  var headers = req.headers,
    cookie = headers['cookie'],
    sid = '';
  if (cookie) {
    var start = cookie.indexOf('sid=');
    if (start != -1) {
      start += 4
      var end = cookie.indexOf(';', start);
      if (end == -1)
        sid = cookie.substring(start);
      else
        sid = cookie.substring(start, end)
    }
  }
  if (sid == '' && res) {
    sid = uuid.v4();
    res.setHeader('Set-Cookie', ['sid=' + sid + ';path=/']);
  }
  if (!sessions[sid]) {
    sessions[sid] = {
      sid
    }
  }
  sessions[sid].lastVisitTime = new Date().getTime();
  req.session = sessions[sid];
  return sessions[sid]
}

exports.clear = (resolve) => {
  resolve = resolve || (() => {
  })
  var nt = new Date().getTime(),
    clear_ids = [];
  for (var sid in sessions) {
    if (nt - sessions[sid].lastVisitTime > config.sessionExpireTime) {
      sessions[sid] = {}
      clear_ids.push(sid)
    }
  }
  resolve(clear_ids)
}

exports.sessions = sessions

setInterval(() => exports.clear(), 120000)